package com.lcredu.seckill.config;

import com.lcredu.seckill.pojo.User;
import com.lcredu.seckill.service.UserService;
import com.lcredu.seckill.util.CookieUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 黎长容
 * @date 2025-08-26 18:19
 * 解析器:从这里可以获取user对象
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Resource
    private UserService userService;

    //只有这个方法返回true才会执行下面的方法

    /**
     * 判断是否支持指定参数的解析
     *
     * @param parameter 方法参数对象，包含参数类型和注解等信息
     * @return 当参数类型为User.class时返回true，否则返回false
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> parameterType = parameter.getParameterType();
        return parameterType == User.class;
    }

    /**
     * 解析方法参数，获取当前登录用户信息
     *
     * @param parameter     方法参数对象
     * @param mavContainer  ModelAndView容器
     * @param webRequest    Web请求对象
     * @param binderFactory 数据绑定工厂
     * @return 解析得到的User对象
     * @throws Exception 解析过程中可能抛出的异常
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Class<?> parameterType = parameter.getParameterType();
//        System.out.println(parameterType);
        // 获取原生HTTP请求和响应对象
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);

        // 从Cookie中获取用户票据
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");

        // 根据用户票据获取用户信息
        User user = userService.getUser(userTicket, request, response);
        return user;
    }

}
